<template>
  <view class="upload-container">
    <view class="header">
      <text class="title">上传测试资源</text>
    </view>

    <view class="content">
      <!-- 图标1上传 -->
      <view class="upload-item">
        <text class="label">图标1</text>
        <view class="upload-box" @tap="chooseImage('icon1')">
          <image v-if="images.icon1" :src="images.icon1" class="preview-img"></image>
          <view v-else class="upload-placeholder">
            <text>点击上传</text>
          </view>
        </view>
      </view>

      <!-- 图标2上传 -->
      <view class="upload-item">
        <text class="label">图标2</text>
        <view class="upload-box" @tap="chooseImage('icon2')">
          <image v-if="images.icon2" :src="images.icon2" class="preview-img"></image>
          <view v-else class="upload-placeholder">
            <text>点击上传</text>
          </view>
        </view>
      </view>

      <!-- 开始测试按钮上传 -->
      <view class="upload-item">
        <text class="label">开始测试按钮</text>
        <view class="upload-box" @tap="chooseImage('startBtn')">
          <image v-if="images.startBtn" :src="images.startBtn" class="preview-img"></image>
          <view v-else class="upload-placeholder">
            <text>点击上传</text>
          </view>
        </view>
      </view>

      <!-- 测试中按钮上传 -->
      <view class="upload-item">
        <text class="label">测试中按钮</text>
        <view class="upload-box" @tap="chooseImage('testingBtn')">
          <image v-if="images.testingBtn" :src="images.testingBtn" class="preview-img"></image>
          <view v-else class="upload-placeholder">
            <text>点击上传</text>
          </view>
        </view>
      </view>
      
      <!-- 首页图片上传 -->
      <view class="upload-item">
        <text class="label">首页图片</text>
        <view class="upload-box" @tap="chooseImage('homePage')">
          <image v-if="images.homePage" :src="images.homePage" class="preview-img"></image>
          <view v-else class="upload-placeholder">
            <text>点击上传</text>
          </view>
        </view>
      </view>

      <!-- 时间范围设置 -->
      <view class="time-range">
        <text class="label">反应时间范围</text>
        <view class="time-inputs">
          <input v-model="timeRange.min" type="number" placeholder="最小秒数" class="time-input">
          <text class="time-separator">-</text>
          <input v-model="timeRange.max" type="number" placeholder="最大秒数" class="time-input">
          <text class="time-unit">秒</text>
        </view>
      </view>
      
      <!-- 停留时间设置 -->
      <view class="time-range">
        <text class="label">停留时间</text>
        <view class="time-inputs">
          <input v-model="displayTime" type="number" placeholder="停留秒数" class="time-input">
          <text class="time-unit">秒</text>
        </view>
      </view>



      <!-- 评价规则设置 -->
      <view class="evaluation-rules">
        <view class="rule-header">
          <text class="label">评价规则设置</text>
          <button class="add-rule-btn" @tap="addEvaluationRule">添加规则</button>
        </view>
        
        <view class="rule-list">
          <view class="rule-item" v-for="(rule, index) in evaluationRules" :key="index">
            <view class="rule-controls">
              <view class="rule-condition">
                <text>反应时间</text>
                <picker v-model="rule.type" mode="selector" range="['gt','lt']" range-key="value">
                  <view class="picker">
                    {{ rule.type === 'gt' ? '大于' : '小于' }}
                  </view>
                </picker>
                <input v-model.number="rule.time" type="number" class="rule-time-input">
                <text>毫秒时</text>
              </view>
              <input v-model="rule.text" class="rule-text-input" placeholder="输入评价文本">
              <button class="delete-rule-btn" @tap="deleteEvaluationRule(index)">删除</button>
            </view>
          </view>
        </view>
      </view>

      <!-- 提交按钮 -->
      <button class="submit-btn" @tap="submitForm" :disabled="!canSubmit">
        提交上传
      </button>
    </view>
  </view>
</template>

<script>
import request from '@/utils/request.js';

export default {
  data() {
    return {
      images: {
        icon1: '',
        icon2: '',
        startBtn: '',
        testingBtn: '',
        homePage: ''
      },
      timeRange: {
        min: 2,
        max: 6
      },
      displayTime: 3,
      // 评价规则配置
      evaluationRules: [],
      uploadTasks: {},
      uploading: false
    };
  },

  computed: {
    canSubmit() {
      // 检查是否所有图片都已上传且时间范围有效，评价规则也需要有效
      const hasValidRules = this.evaluationRules.length > 0 && 
        this.evaluationRules.every(rule => rule.time && rule.text && (rule.type === 'gt' || rule.type === 'lt'));
        
      return this.images.icon1 &&
        this.images.icon2 &&
        this.images.startBtn &&
        this.images.testingBtn &&
        this.images.homePage &&
        this.timeRange.min &&
        this.timeRange.max &&
        this.displayTime &&
        hasValidRules &&
        this.timeRange.min < this.timeRange.max &&
        !this.uploading;
    }
  },

  onLoad() {
    // 页面加载时从API获取数据
    this.loadSavedData();
  },
  
  methods: {
    // 加载已保存的数据
    loadSavedData() {
      const _this = this;
      _this.uploading = true;
      
      request({
        url: '/api.php',
        method: 'GET',
        header: {
          'Content-Type': 'application/json'
        }
      }).then(res => {
        if (res.code === 0 && res.data) {
          // 直接使用返回的数据对象
          const latestData = res.data;
          
          // 更新页面数据
          if (latestData.images) {
            _this.images = latestData.images;
          }
          if (latestData.timeRange) {
            _this.timeRange = latestData.timeRange;
          }
          if (latestData.displayTime) {
            _this.displayTime = latestData.displayTime;
          }
          // 更新评价规则
          if (latestData.evaluationRules && Array.isArray(latestData.evaluationRules)) {
            _this.evaluationRules = latestData.evaluationRules;
          } else {
            // 设置默认评价规则
            _this.evaluationRules = [
              { type: 'gt', time: 2000, text: '九灵奶奶！聆听指挥的亲切问候吧' },
              { type: 'lt', time: 250, text: '简直就是蓝调在世！' },
              { type: 'lt', time: 280, text: '超级九灵！这还说啥了兄弟' },
              { type: 'lt', time: 320, text: '顶级操作手！烧得少基本上是对局安排的问题' },
              { type: 'lt', time: 400, text: '九灵操作手！20岁的九灵，18岁的她' },
              { type: 'lt', time: 500, text: '甲一九灵！老师老师，你烧得这么快跟谁学的？我在抖音跟音免学的' },
              { type: 'lt', time: 700, text: '甲组九灵！可以可以，九灵的未来' },
              { type: 'lt', time: 1000, text: '九灵妈妈！嗯...至少会烧' }
            ];
          }
        }
      }).catch(err => {
        console.error('加载数据失败:', err);
      }).finally(() => {
        _this.uploading = false;
      });
    },
    
    // 选择图片
    chooseImage(type) {
      const _this = this;

      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: function (res) {
          const tempFilePath = res.tempFilePaths[0];
          _this.uploadImage(type, tempFilePath);
        },
        fail: function (err) {
          console.error('选择图片失败:', err);
          uni.showToast({
            title: '选择图片失败',
            icon: 'none'
          });
        }
      });
    },

    // 上传图片到服务器
    uploadImage(type, filePath) {
      const _this = this;
      _this.uploading = true;

      // 显示加载提示
      uni.showLoading({
        title: '上传中...'
      });

      // 使用uni.uploadFile上传图片到本地API
      // 注意：这里只上传图片，不提交时间数据
      const uploadTask = uni.uploadFile({
        url: request.baseUrl + '/api.php',
        filePath: filePath,
        name: type,
        header: {},
        formData: {
          'upload_type': 'image_only'
        },
        success: function (res) {
          try {
            const data = JSON.parse(res.data);
            if (data.code === 0 && data.data) {
              // 保存返回的图片URL
              if (data.data && data.data.images && data.data.images[type]) {
                _this.images[type] = data.data.images[type];
              } else if (data.data && data.data.images && Array.isArray(data.data.images) && data.data.images.length > 0) {
                // 兼容可能返回的数组格式
                _this.images[type] = data.data.images[0][type] || '';
              } else if (data.data && typeof data.data === 'string') {
                // 兼容只返回URL字符串的情况
                _this.images[type] = data.data;
              }
              console.log('更新后的images数据:', _this.images);
              uni.showToast({
                title: '上传成功',
                icon: 'success'
              });
            } else {
              throw new Error(data.message || '上传失败');
            }
          } catch (error) {
            console.error('上传失败:', error);
            uni.showToast({
              title: '上传失败',
              icon: 'none'
            });
          }
        },
        fail: function (err) {
          console.error('上传请求失败:', err);
          uni.showToast({
            title: '网络异常',
            icon: 'none'
          });
        },
        complete: function () {
          _this.uploading = false;
          uni.hideLoading();
        }
      });

      // 保存上传任务，以便可以中止
      _this.uploadTasks[type] = uploadTask;
    },

    // 添加新的评价规则
    addEvaluationRule() {
      this.evaluationRules.push({ type: 'lt', time: 500, text: '新评价规则' });
    },
    
    // 删除评价规则
    deleteEvaluationRule(index) {
      this.evaluationRules.splice(index, 1);
    },
    
    // 排序规则，保证顺序正确（大于规则在前，小于规则按时间降序）
    sortRules() {
      this.evaluationRules.sort((a, b) => {
        if (a.type !== b.type) {
          return a.type === 'gt' ? -1 : 1; // gt在前，lt在后
        }
        // 对于相同类型，lt按时间降序，gt按时间升序
        return a.type === 'lt' ? b.time - a.time : a.time - b.time;
      });
    },
    
    // 提交表单数据
    submitForm() {
      if (!this.canSubmit) return;
      
      // 提交前排序规则
      this.sortRules();

      const _this = this;
      _this.uploading = true;

      uni.showLoading({
        title: '提交中...'
      });

      // 提交完整表单数据（包含所有图片信息、时间设置和评价规则）
      request({
        url: '/api.php',
        method: 'POST',
        data: {
          upload_type: 'submit_form',
          min_time_range: this.timeRange.min,
          max_time_range: this.timeRange.max,
          display_time: this.displayTime,
          images: this.images,
          evaluationRules: this.evaluationRules
        },
        header: {
          'Content-Type': 'application/json'
        }
      }).then(res => {
        if (res.code === 0) {
          uni.showToast({
            title: '提交成功',
            icon: 'success'
          });

          // 延迟返回上一页
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          throw new Error(res.message || '提交失败');
        }
      }).catch(err => {
        console.error('提交失败:', err);
        uni.showToast({
          title: err.message || '提交失败',
          icon: 'none'
        });
      }).finally(() => {
        _this.uploading = false;
        uni.hideLoading();
      });
    }
  }
};
</script>

<style scoped>
.upload-container {
  width: 100%;
  min-height: 100vh;
  background-color: #f9f9f9;
  padding-bottom: 40rpx;
}

.header {
  background-color: #fff;
  padding: 20rpx 0;
  text-align: center;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  margin-bottom: 20rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.content {
  padding: 0 30rpx;
}

.upload-item {
  margin-bottom: 30rpx;
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.label {
  display: block;
  font-size: 28rpx;
  color: #666;
  margin-bottom: 20rpx;
}

.upload-box {
  width: 200rpx;
  height: 200rpx;
  border: 2rpx dashed #ddd;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
}

.preview-img {
  width: 100%;
  height: 100%;
  border-radius: 6rpx;
}

.upload-placeholder {
  text-align: center;
  color: #999;
}

.upload-placeholder text {
  font-size: 24rpx;
}

.time-range {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.time-inputs {
  display: flex;
  align-items: center;
  margin-top: 20rpx;
}

.time-input {
  width: 120rpx;
  height: 70rpx;
  border: 2rpx solid #ddd;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  text-align: center;
}

.time-separator {
  margin: 0 20rpx;
  font-size: 32rpx;
  color: #333;
}

.time-unit {
  margin-left: 20rpx;
  font-size: 28rpx;
  color: #666;
}

.submit-btn {
  background-color: #07c160;
  color: #fff;
  font-size: 32rpx;
  height: 90rpx;
  line-height: 90rpx;
  border-radius: 45rpx;
  margin-top: 40rpx;
}

.submit-btn:disabled {
  background-color: #ccc;
}

/* 评价规则样式 */
.evaluation-rules {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.rule-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.add-rule-btn {
  background-color: #07c160;
  color: #fff;
  font-size: 24rpx;
  height: 60rpx;
  line-height: 60rpx;
  padding: 0 30rpx;
}

.rule-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.rule-item {
  border: 2rpx solid #eee;
  border-radius: 8rpx;
  padding: 20rpx;
  background-color: #fafafa;
}

.rule-controls {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}

.rule-condition {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10rpx;
}

.picker {
  width: 100rpx;
  height: 60rpx;
  border: 2rpx solid #ddd;
  border-radius: 6rpx;
  font-size: 24rpx;
  line-height: 60rpx;
  text-align: center;
}

.rule-time-input {
  width: 120rpx;
  height: 60rpx;
  border: 2rpx solid #ddd;
  border-radius: 6rpx;
  padding: 0 15rpx;
  font-size: 24rpx;
  text-align: center;
}

.rule-text-input {
  width: 100%;
  height: 70rpx;
  border: 2rpx solid #ddd;
  border-radius: 6rpx;
  padding: 0 20rpx;
  font-size: 26rpx;
}

.delete-rule-btn {
  background-color: #ff4d4f;
  color: #fff;
  font-size: 24rpx;
  height: 60rpx;
  line-height: 60rpx;
  padding: 0 30rpx;
  align-self: flex-end;
}
</style>